package com.service;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;

@Service
public class MiaoshaService {

    @Autowired
    private RedisTemplate redisTemplate;

    private AtomicInteger  atomicInteger = new AtomicInteger(10);

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 这个不行，会超卖
     */
    public void miaoshNoLock()
    {
        //从redis中取出goods数量
        Integer goods = (Integer)redisTemplate.boundValueOps("goods").get();

        if (goods>0)
        {
            goods--;
            System.out.println(goods);
            redisTemplate.boundValueOps("goods").set(goods);
        }

    }

    /**
     * 单服务器解决方案
     */
    public synchronized   void miaoshThreadSynchonize()
    {
        //从redis中取出goods数量
        Integer goods = (Integer)redisTemplate.boundValueOps("goods").get();

        if (goods>0)
        {
            int newGoods = atomicInteger.decrementAndGet();
            System.out.println(newGoods);
            redisTemplate.boundValueOps("goods").set(newGoods);
        }

    }

    /**
     * 集群环境
     */
    public   void miaoshJiqun()
    {
        RLock rLock = redissonClient.getLock("miaosha");
        rLock.lock(); //一直等待
            //从redis中取出goods数量
            Integer goods = (Integer)redisTemplate.boundValueOps("goods").get();

            if (goods>0)
            {
                int newGoods = atomicInteger.decrementAndGet();
                System.out.println(newGoods);
                redisTemplate.boundValueOps("goods").set(newGoods);
            }

            //发一条消息到消息队列

        rLock.unlock();



    }







}













